package com.chat.db.nosql.redis;

import com.chat.db.DbLinkConfigBean;
import com.chat.db.Session;
import com.chat.db.nosql.NoSqlSessionFactory;
import com.chat.db.nosql.redis.cluster.JedisClusterConfig;
import com.chat.db.nosql.redis.single.JedisConfig;

public class RedisSessionFactory extends NoSqlSessionFactory {

    private JedisConfig db;
    private JedisClusterConfig cluster;

    public RedisSessionFactory(RedisConfiguration configuration) {
        super();

        this.config = configuration;

        initDb();
    }

    private void initDb() {
        if (db == null) {
            // TODO 以后可以使用集群处理,单机连接并获取哨兵模式中的主机
            String[] hostAndPort = config.getDbConfig().getHosts().split(DbLinkConfigBean.PORT_SEPARATOR);
            db = new JedisConfig(hostAndPort[0],
                    hostAndPort.length > 1 && hostAndPort[1].length() > 0 ? Integer.parseInt(hostAndPort[1]) : DbLinkConfigBean.REDIS_DEFAULT_PORT,
                    config.getDbConfig().getPassword());
        }
        if (!config.getDbConfig().getIsSingle() && cluster == null) {
            cluster = new JedisClusterConfig(config.getDbConfig().getClusterHosts(),
                    DbLinkConfigBean.REDIS_DEFAULT_PORT, config.getDbConfig().getPassword());
        }
    }

    @Override
    public Session openSession() {
        // TODO 加入连接检测,连接不成功枚举所有有事务的机子进行尝试
        return new RedisSession(new DbRedis(db.getJedis(),
                config.getDbConfig().getIsSingle() ? null : cluster.getJedisCluster(),
                config.getDbConfig().getIsSingle()));
    }
}
